import os
import zipfile
import tarfile
import argparse

# 网页填充内容
bisheng_optimization = [[1, "函数库优化", "标量数学库(mathlib)", "未使用"],
                        [2, "函数库优化", "矢量数学库(veclib=MATHLIB)", "未使用"],
                        [3, "函数库优化", "内存优化库(jemalloc)", "未使用"],
                        [4, "函数库优化", "neon指令字符优化库(stringlib)", "未使用"],
                        [5, "函数库优化", "sve指令字符优化库(stringlib)", "未使用"],
                        [6, "Continuous Feature Guided Optimization", "反馈优化(PGO)", "未使用"],
                        [7, "Continuous Feature Guided Optimization", "二进制优化(BOLG)", "未使用"],
                        [8, "AI4Compiler", "autotuner", "未使用"]]
# 每行同时出现关键字，才认定开启优化
bisheng_optimization_keyword = [
    ["-lmathlib"],
    ["-lmathlib", "-fveclib=MATHLIB"],
    ["-ljemalloc"],
    ["-lstringlib", "_aarch64_simd"],
    ["-lstringlib", "_aarch64_sve"],
    ["-fprofile-use"],
    ["llvm-bolt"],
    ["-fautotune"],
]

tuner_report_info = [{'label': '门禁工具', 'value': '毕昇编译器验收工具'},
                     {'label': '评估结果', 'value': '不通过'}]


class AcceptanceBiShengTool(object):

    def __init__(self, output=None):
        self.result = {
            "Devkit工具": {
                "编译构建": {
                    "毕昇编译器": [
                        {"AI4Compiler": "通过"},
                        {"反馈编译优化（CFGO)": "通过"},
                        {"自动系统库优化": "通过"}
                    ]
                }
            }

        }
        self.output = output

    def check_keywords_in_lines(self, content, keywords):
        lines = content.splitlines()
        for line in lines:
            if all(keyword in line for keyword in keywords):
                return True
        return False

    def devkit_acceptance_report(self, compressed_report_package):
        if not os.path.exists(compressed_report_package):
            print("Enter a correct report package.")
            return
        file_ext = os.path.splitext(compressed_report_package)[1].lower()
        if file_ext not in (".zip", ".gz", ".bz2"):
            print("Please use the compressed package in the following format:.zip、.gz、.bz2")
            return
        decompress = {".zip": decompress_zip, ".gz": decompress_gz_bz, ".bz2": decompress_gz_bz}
        current_path = os.getcwd()
        file_names = decompress.get(file_ext)(compressed_report_package)
        for file in file_names:
            try:
                if not os.path.isfile(os.path.join(current_path, file)):
                    continue
                with open(os.path.join(current_path, file), 'r', encoding='utf-8') as f:
                    content = f.read()
                    for i in range(len(bisheng_optimization_keyword)):
                        keywords = bisheng_optimization_keyword[i]
                        if self.check_keywords_in_lines(content, keywords):
                            bisheng_optimization[i][3] = "已使用"
                            tuner_report_info[1]["value"] = "通过"

            except (UnicodeDecodeError, PermissionError):
                continue

        originals = """
                <html>
                <head>
                <meta charset="utf-8"/>
                <meta content="IE=edge" http-equiv="X-UA-Compatible"/>
                <meta content="width=device-width, initial-scale=1.0" name="viewport"/>
                <title>Document</title>
                </head>
                <body>
                <div class="header">
                      毕昇编译器验收报告
                    </div>
                <div class="content">
                <div class="title">
                        配置信息
                      </div>
                <div class="info">
                <div class="left">
                <div class="left-content">
                </div>
                </div>
                <div class="right">
                <div class="text"></div>
                <div class="num"></div>
                </div>
                </div>
                <div class="table">
                <div class="title">验收详细结果</div>
                <table>
                <tr>
                <th>序号</th>
                <th>优化项</th>
                <th>使用状态</th>
                </tr>
                </table>
                </div>
                </div>
                </body>
                <script>    
                            var infoList = {};

                            // 已使能特性
                            var num = "";

                            // 验收详细结果
                            var tableList = {};




                    // 配置信息
                    var leftContentEle = document.getElementsByClassName('left-content')[0];
                     infoList.forEach(item => {{
                       let singleEle = document.createElement('div');
                       singleEle.setAttribute('class', 'single');
                       let labelEle = document.createElement('div');
                       labelEle.setAttribute('class', 'label');
                       labelEle.innerText = item.label;
                       let valueEle = document.createElement('div');
                       valueEle.setAttribute('class', 'value');
                       valueEle.innerText = item.value;
                     
                       singleEle.appendChild(labelEle);
                       singleEle.appendChild(valueEle);
                       leftContentEle.appendChild(singleEle);
                     }})


                    // 已使能特性
                    var numEle = document.getElementsByClassName('num')[0];
                    numEle.innerText = num;


                    // 验收详细结果
                    var tableEle = document.getElementsByTagName('table')[0];
                    tableList.forEach(list => {{
                      let trEle = document.createElement('tr');
                      list.forEach(item => {{
                        let tdEle = document.createElement('td');
                        tdEle.innerText = item;
                        trEle.appendChild(tdEle);
                      }})
                      tableEle.appendChild(trEle);
                    }})


                  </script>
                <style>
                    body {{
                      background-color: #222020;
                      color: #fff;
                      padding: 8px 16px;
                      margin: 0;
                      font-size: 14px;
                    }}
                    .header {{
                      font-size: 18px;
                      width: 100%;
                      line-height: 50px;
                      border-bottom: 1px solid rgb(110, 110, 110);
                    }}
                    .info {{
                      display: flex;
                      justify-content: flex-start;
                      align-items: flex-start;
                    }}
                    .left {{
                      width: 60%;
                    }}
                    .title {{
                      font-size: 16px;
                      margin: 20px 0 10px 0;
                    }}
                    .single {{
                      display: flex;
                      justify-content: flex-start;
                      align-items: center;
                      margin: 8px 0;
                    }}
                    .label {{
                      color: rgb(195, 206, 216);
                      width: 30%;
                    }}
                    .right {{
                      width: 40%;
                      text-align: center;
                    }}
                    .text {{
                      font-size: 20px;
                      color: rgb(195, 206, 216);
                    }}
                    .num {{
                      font-size: 50px;
                    }}
                    table {{
                      border: 1px solid rgb(110, 110, 110);
                      width: 100%
                    }}
                    th{{
                      font-size: 14px; 
                      padding: 5px 15px;
                      color: rgb(222, 227, 231);
                      background-color: #555353;
                    }}
                    td {{
                      padding: 2px 5px;
                      border-top: 1px solid rgb(110, 110, 110);
                      border-right: 1px solid rgb(110, 110, 110);
                    }}
                    td:last-child {{
                      border-right: none
                    }}
                  </style>
                </html>"""
        bisheng_detail_info = []
        if "已使用" in [bisheng_optimization[0][3], bisheng_optimization[1][3], bisheng_optimization[2][3],
                        bisheng_optimization[3][3], bisheng_optimization[4][3]]:
            automatic = [1, "自动系统库优化", "已使用"]
            self.result["Devkit工具"]["编译构建"]["毕昇编译器"][2]["自动系统库优化"] = "通过"
        else:
            automatic = [1, "自动系统库优化", "未使用"]
            self.result["Devkit工具"]["编译构建"]["毕昇编译器"][2]["自动系统库优化"] = "不通过"
        bisheng_detail_info.append(automatic)
        if "已使用" in [bisheng_optimization[5][3], bisheng_optimization[6][3]]:
            cfgo = [2, "反馈编译优化（CFGO)", "已使用"]
            self.result["Devkit工具"]["编译构建"]["毕昇编译器"][1]["反馈编译优化（CFGO)"] = "通过"
        else:
            cfgo = [2, "反馈编译优化（CFGO)", "未使用"]
            self.result["Devkit工具"]["编译构建"]["毕昇编译器"][1]["反馈编译优化（CFGO)"] = "不通过"
        bisheng_detail_info.append(cfgo)
        if bisheng_optimization[7][3] == "已使用":
            bisheng_detail_info.append([3, "AI4Compiler", "已使用"])
            self.result["Devkit工具"]["编译构建"]["毕昇编译器"][0]["AI4Compiler"] = "通过"
        else:
            bisheng_detail_info.append([3, "AI4Compiler", "未使用"])
            self.result["Devkit工具"]["编译构建"]["毕昇编译器"][0]["AI4Compiler"] = "不通过"
        if self.output:
            print(self.result)
        else:
            tuner_report_html = originals.format(tuner_report_info, bisheng_detail_info)
            with open(os.path.join(current_path, "毕昇编译器验收工具.html"), "w", encoding="utf-8") as f:
                f.write(tuner_report_html)
            print("View the report in {}.".format(current_path))


def decompress_zip(compressed_report_package, file_list=[]):
    with zipfile.ZipFile(compressed_report_package, 'r') as zip:
        zip.extractall("./")
        for file in zip.namelist():
            if file.endswith('.zip'):
                decompress_zip(file)
    file_names = zip.namelist()
    file_list.extend(file_names)
    return file_list


def decompress_gz_bz(compressed_report_package):
    file_list = []
    with tarfile.open(compressed_report_package, "r") as tar:
        tar.extractall(path="./")
        file_names = tar.getnames()
        for file in file_names:
            if file.endswith('.zip'):
                decompress_zip(file, file_list=file_list)
        file_list.extend(file_names)
        return file_list
